﻿namespace PhoneFilter.Helper
{
    using mshtml;
    using System;
    using System.IO;
    using System.Windows.Forms;

    public static class WebBrowserHelper
    {
        public static HtmlElement CreateJSElement(HtmlDocument tempDocument, string script)
        {
            if (tempDocument != null)
            {
                HtmlElement element = tempDocument.CreateElement("script");
                IHTMLScriptElement domElement = element.DomElement as IHTMLScriptElement;
                domElement.type = "text/javascript";
                domElement.text = script;
                return element;
            }
            return null;
        }

        public static HtmlDocument getDocFromWebBrowser(WebBrowser wb, string url)
        {
            HtmlDocument document = wb.Document;
            if (document != null)
            {
                if (document.Url.ToString().IndexOf(url) > 0)
                {
                    return document;
                }
                int count = wb.Document.Window.Frames.Count;
                if (count > 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        HtmlDocument document2 = wb.Document.Window.Frames[i].Document;
                        if (document2.Url.ToString().IndexOf(url) > 0)
                        {
                            return document2;
                        }
                    }
                }
            }
            return null;
        }

        public static HtmlElement GetElementByKeyWord(HtmlDocument doc, string tagName, string keyWord)
        {
            HtmlElementCollection elementsByTagName = doc.GetElementsByTagName(tagName);
            if (elementsByTagName != null)
            {
                foreach (HtmlElement element in elementsByTagName)
                {
                    if (element.InnerHtml.Contains(keyWord))
                    {
                        return element;
                    }
                }
            }
            return null;
        }

        public static HtmlElement LoadAndCreateLocationJS(HtmlDocument tempDocument, string filePath)
        {
            HtmlElement element;
            try
            {
                using (StreamReader reader = File.OpenText(filePath))
                {
                    element = CreateJSElement(tempDocument, reader.ReadToEnd());
                }
            }
            catch
            {
                element = null;
            }
            return element;
        }
    }
}

